package com.xy6.jvm.thread.string;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 并发集合示例
 * 
 * @author zhang
 * @since 2018-05-04
 */
public class Intern {

	/**
	 * key不能为null
	 * hashmap的key可以为null
	 */
	private static final ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>();
	
	public static String intern(String s){
		String result = map.get(s);
		if(result == null){
			result = map.putIfAbsent(s, s);
			if(result == null){
				result = s;
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		System.out.println(intern("hello1"));
		System.out.println(map);
		System.out.println(intern("hello2"));
		System.out.println(map);
		System.out.println(intern("hello1"));
		System.out.println(map);
	}

}
